package xm.chengdu.com.beijing_211;

import android.app.Activity;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothSocket;
import android.content.DialogInterface;
import android.content.DialogInterface.OnKeyListener;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Handler.Callback;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.github.czy1121.view.RoundButton;
import com.sdwfqin.cbt.CbtManager;

import java.io.IOException;
import java.nio.charset.Charset;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import Threads.BluetoothCommunicateThread2;
import base.BaseApplication;
import base.Z_Login_UserInfoDao;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import de.greenrobot.event.EventBus;
import ui.InputDialog;

import com.sdwfqin.cbt.Content;

import utils.FaSong;
import utils.JX_Utils;
import utils.SpfUtils;
import utils.WW;

public class MainActivity extends Activity {
    ProgressDialog dialog = null;
    public static BluetoothAdapter btAdapter = BluetoothAdapter
            .getDefaultAdapter();
    // 所有配置文件名称
    public static Map<String, String> map = new HashMap<String, String>();
    public static final String SPP_UUID = "00001101-0000-1000-8000-00805F9B34FB";
    public static BluetoothSocket btSocket = null;
    // public static BluetoothConnectThread btConnThread = null;
    public static BluetoothCommunicateThread2 btCommThread;
    //    Button button1;


    boolean ishow = true;


    @BindView(R.id.layout_zuo)
    RelativeLayout layoutZuo;
    @BindView(R.id.textView2)
    TextView textView2;
    @BindView(R.id.layout_zhong)
    RelativeLayout layoutZhong;

    @BindView(R.id.layout_you)
    RelativeLayout layoutYou;
    @BindView(R.id.layout_szmx)
    LinearLayout layoutSzmx;

    @BindView(R.id.mimi2)
    TextView mimi2;
    @BindView(R.id.mimi0)
    TextView mimi0;
    @BindView(R.id.mimi3)
    TextView mimi3;
    @BindView(R.id.cyzgz)
    TextView cyzgz;
    @BindView(R.id.jr_sp)
    Spinner jrSp;
    @BindView(R.id.mimi)
    TextView mimi;
    @BindView(R.id.fwjdkh)
    TextView fwjdkh;
    @BindView(R.id.yc_sp)
    Spinner ycSp;
    @BindView(R.id.fwjdkh2)
    TextView fwjdkh2;
    @BindView(R.id.ss_sp)
    Spinner ssSp;
    @BindView(R.id.fwjdkh211)
    TextView fwjdkh211;
    @BindView(R.id.mimi4)
    TextView mimi4;
    @BindView(R.id.mimi5)
    TextView mimi5;
    @BindView(R.id.bk_sp)
    Spinner bkSp;
    @BindView(R.id.bt_getCode3)
    RoundButton btGetCode3;
    @BindView(R.id.bt_send)
    RoundButton btSend;


    @BindView(R.id.dianliang)
    ImageView dianliangs;


    Z_Login_UserInfoDao z_login_userInfoDao;
    String dian = "";
    boolean first = false;
    Handler handler = new Handler(new Callback() {

        @Override
        public boolean handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    Content.isConn = true;
                    Content.shoudaomima = false;
                    ishow = true;
                    Toast.makeText(MainActivity.this, "Connection successful", Toast.LENGTH_SHORT).show();
                    if (dialog != null) {
                        dialog.dismiss();
                    }
                    startComm();
                    MyEvent myEvent = new MyEvent();
                    myEvent.setType("finish");
                    EventBus.getDefault().post(myEvent);


                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            chaxunmima();
                        }
                    }, 1500);
                    if (!first) {
                        Log.e("98888", "走了");
                        mHandler.postDelayed(r, 5000);//延时100毫秒
                        first = true;
                    }
//                    else {
//                        Content.shoudaomima = true;
//                    }

                    break;
                case 2:
                    Toast.makeText(MainActivity.this, "Connection failed", Toast.LENGTH_SHORT).show();
                    if (dialog != null) {
                        dialog.dismiss();
                    }
                    break;
                case 4:
//                    Toast.makeText(MainActivity.this, "Data validation failed", Toast.LENGTH_SHORT).show();
                    if (dialog != null) {
                        dialog.dismiss();
                    }
                    break;
                case 3:
                    String str3 = (String) msg.obj;
                    Log.e("androidzhi", "收到数据" + str3);

                    jiejiexixi(str3);

                    break;


                default:
                    break;
            }
            return false;
        }
    });

    public void jiejiexixi(String str3) {
        mimi2.setText("收到数据：" + str3);
        if (str3.startsWith("55AA")) {

            String changdu = str3.substring(6, 8);
            int i = Integer.parseInt(changdu, 16);
            String substring2 = str3.substring(8, str3.length() - 2);
            if (substring2.length() != i * 2) {
                Toast.makeText(MainActivity.this, "Protocol package length detection does not pass", Toast.LENGTH_SHORT).show();
                return;
            }


            String substring1 = str3.substring(0, str3.length() - 2);
            String jiegguo = WW.makeChecksum(substring1);
            //计算的值
            String substrings = jiegguo.substring(jiegguo.length() - 2, jiegguo.length());
            String shoudaode = str3.substring(str3.length() - 2, str3.length());
            Integer xxx = Integer.parseInt(substrings, 16);
            Integer xxxs = Integer.parseInt(shoudaode, 16);

            if (!xxx.equals(xxxs)) {
//                            Toast.makeText(MainActivity.this, "Data validation failed", Toast.LENGTH_SHORT).show();
                return;
            }
            String guanjianzi = str3.substring(4, 6);
            if (!guanjianzi.equals("07")) {
                String mima = (String) SpfUtils.get(BaseApplication.getInstance(), "mima", "010203040506");
                String substring3 = str3.substring(8, 20);

                if (!mima.equals(substring3)) {

                    Toast.makeText(MainActivity.this, "pincode err", Toast.LENGTH_SHORT).show();
                    return;
                }
            }


//                          55aa 01 10 080808080808 010100030300000106004f
//                        55AA 01 10 010203040506 0155550000000330020005

            Log.e("88", "关键字" + guanjianzi);
            if (guanjianzi.equals("01")) {
                //心跳检测
//                            Toast.makeText(MainActivity.this, str3, Toast.LENGTH_SHORT).show();
                String chenggg = str3.substring(str3.length() - 4, str3.length() - 2);

                if (chenggg.equals("00")) {
//                                Toast.makeText(MainActivity.this, "心跳成功", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(MainActivity.this, "Heart failure.", Toast.LENGTH_SHORT).show();
                    return;
                }
                String substring0 = str3.substring(20, 22);


//                            55AA 01 10 010203040506 0155550000000330020005
                String gecaozhuangtaione = str3.substring(22, 24);
                String gecaozhuangtaitwo = str3.substring(24, 26);
                String one = JX_Utils.hexString2binaryString(gecaozhuangtaione);
                Log.e("888", "xx" + one);
                String two = JX_Utils.hexString2binaryString(gecaozhuangtaitwo);
                Log.e("888", "xx" + two);
                String zhuangtaione = jiexi1(one);
                String zhuangtaitwo = jiexi2(two);
                String dians = str3.substring(28, 30);
                if (dians.equals("01")) {
                    Content.ischongdian = "chong";
                } else if (dians.equals("00")) {
                    Content.ischongdian = "weichong";
                }

                String substringthree = str3.substring(30, 32);
                if (substringthree.equals("00")) {
                    Content.chongdianzhuangtai = "normal";
//                                mimi3.setText("充电站状态：正常");
                    dian = "";
                } else if (substringthree.equals("55")) {
//                                mimi3.setText("充电站状态：边界线断开");
                    Content.chongdianzhuangtai = "Boundary line disconnection";
                    dian = Content.chongdianzhuangtai;
                } else if (substringthree.equals("58")) {
                    Content.chongdianzhuangtai = "Power disconnection";
                    dian = Content.chongdianzhuangtai;
//                                mimi3.setText("充电站状态：电源断开");
                }
                Date date = new Date();
                mimi.setText("异常:" + zhuangtaione + "," + zhuangtaitwo + "," + dian);
                if (!zhuangtaione.equals("Robots working normally")) {
                    Content.ischongdian = "err";
                    String s = zhuangtaione + "," + zhuangtaitwo + ",";
                    if (s.equals(",,")) {
                        z_login_userInfoDao.addUser("Work abnormally," + dian, sdf.format(date));
                    }  else{
                        z_login_userInfoDao.addUser(zhuangtaione + "," + zhuangtaitwo + "," + dian, sdf.format(date));
                    }

                }

                String substringfour = str3.substring(32, 34);
                String s3 = jiexi3(substringfour);
//                            mimi2.setText("工作模式：" + s3);
                Content.gongzuomoshi = s3;
                String dianliang = str3.substring(34, 36);
                Log.e("电量", "电：" + dianliang);
                Integer x = Integer.parseInt(dianliang, 16);
                if (x == 0) {
                    dianliangs.setImageResource(R.drawable.dianliang0);

                } else if (x > 0 && x <= 20) {
                    dianliangs.setImageResource(R.drawable.dianliang_020);

                } else if (x > 20 && x <= 40) {
                    dianliangs.setImageResource(R.drawable.dianliang40);

                } else if (x > 40 && x <= 60) {
                    dianliangs.setImageResource(R.drawable.dianliang60);

                } else if (x > 60 && x <= 80) {
                    dianliangs.setImageResource(R.drawable.dianliang80);

                } else if (x > 80 && x <= 100) {
                    dianliangs.setImageResource(R.drawable.dianliang100);

                }
//                            mimi4.setText("电量：" + x);
                Content.dianliang = "" + x;
                String gecaoshengyu = str3.substring(36, 38);
                Integer gecaoshengyus = Integer.parseInt(gecaoshengyu, 16);
                mimi5.setText("割草剩余：" + gecaoshengyus);
                Content.gecaoshengyu = "" + x;

            } else if (guanjianzi.equals("02")) {
                //查询产品信息
                return;
            } else if (guanjianzi.equals("03")) {
                //设置时间
                String substring = str3.substring(20, 22);
                Log.e("88", "设置时间" + substring);
                if (substring.equals("00")) {
                    MyEvent events4 = new MyEvent();
                    events4.setType("settingsuccess");
                    EventBus.getDefault().post(events4);
                    Toast.makeText(MainActivity.this, "Setting time successful！", Toast.LENGTH_SHORT).show();
                } else {
                    MyEvent events4 = new MyEvent();
                    events4.setType("settingerr");
                    EventBus.getDefault().post(events4);
                    Toast.makeText(MainActivity.this, "Setting time failed！", Toast.LENGTH_SHORT).show();
                }
            } else if (guanjianzi.equals("04")) {
                //预约下发
                String substring = str3.substring(20, 22);
                Log.e("88", "预约下发" + substring);
                if (substring.equals("00")) {
                    MyEvent events4 = new MyEvent();
                    events4.setType("settingsuccess");
                    EventBus.getDefault().post(events4);

                    Toast.makeText(MainActivity.this, "Appointment issued successfully！", Toast.LENGTH_SHORT).show();
                } else {
                    MyEvent events4 = new MyEvent();
                    events4.setType("settingerr");
                    EventBus.getDefault().post(events4);
                    Toast.makeText(MainActivity.this, "Booking failed！", Toast.LENGTH_SHORT).show();
                }
            } else if (guanjianzi.equals("05")) {
                //设置工作模式
                String substring = str3.substring(20, 22);
                Log.e("88", "设置工作模式" + substring);
                if (substring.equals("00")) {
                    Toast.makeText(MainActivity.this, "Setting Working Mode Successful！", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(MainActivity.this, "Setting Working Mode failed！", Toast.LENGTH_SHORT).show();
                }

            } else if (guanjianzi.equals("06")) {
                //设置分区域割草时间
                String substring = str3.substring(20, 22);
                Log.e("88", "设置分区域割草时间" + substring);
                if (substring.equals("00")) {
//                                String kaijiqueren = FaSong.kaijiquerenxiafa();
                    MyEvent events4 = new MyEvent();
                    events4.setType("settingsuccess");
                    EventBus.getDefault().post(events4);
                    Toast.makeText(MainActivity.this, "Setting time for sub-region mowing successful！", Toast.LENGTH_SHORT).show();
                } else {
                    MyEvent events4 = new MyEvent();
                    events4.setType("settingerr");
                    EventBus.getDefault().post(events4);
                    Toast.makeText(MainActivity.this, "Failed to set time for sub-region mowing！", Toast.LENGTH_SHORT).show();
                }
            } else if (guanjianzi.equals("07")) {
                //设置密码回复
                String substring = str3.substring(20, 22);
//                            55 AA 07 07 01 01 01 01 01 01 00 13
                Log.e("88", "设置密码成功" + substring);
                if (substring.equals("00")) {
                    String substring5 = str3.substring(8, 20);
                    SpfUtils.put(BaseApplication.getInstance(), "mima", substring5);
                    MyEvent events5 = new MyEvent();
                    events5.setType("settingsuccess");
                    EventBus.getDefault().post(events5);
                    chaxunmima();
//                                String yuyueshibaishangbao = FaSong.mimahuifu();
//                                MyEvent events4 = new MyEvent();
//                                events4.setType("message");
//                                events4.setContent(yuyueshibaishangbao);
//                                EventBus.getDefault().post(events4);
//                                shoudaomima =true;
                    Toast.makeText(MainActivity.this, "Password settings successfully！" + substring5, Toast.LENGTH_SHORT).show();
                } else {
                    MyEvent events4 = new MyEvent();
                    events4.setType("settingerr");
                    EventBus.getDefault().post(events4);
                    Toast.makeText(MainActivity.this, "Password settings unsuccessfully！", Toast.LENGTH_SHORT).show();
                }
            } else if (guanjianzi.equals("08")) {
                //查询密码
                String substring = str3.substring(20, 22);
                Log.e("88", "查询密码" + substring);
                if (substring.equals("00")) {
                    String mimas = str3.substring(8, 20);

                    String yuyueshibaishangbao = FaSong.mimahuifu();
                    MyEvent events4 = new MyEvent();
                    events4.setType("message");
                    events4.setContent(yuyueshibaishangbao);
                    EventBus.getDefault().post(events4);
//                                55 AA 08 07 08 08 08 08 08 08 00 3E

                    if (ishow) {

                        if (!TextUtils.isEmpty(mimas) && mimas.equals("010203040506")) {
                            type("Please set the password.", 1, mimas);
                        } else {
                            type("Please enter your password.", 2, mimas);
                        }
                        ishow = false;
                    }

//
                } else {
//
                }
            } else if (guanjianzi.equals("09")) {
                //设置开机是否需要APP确认
                String substring = str3.substring(20, 22);
                Log.e("88", "设置开机是否需要APP确认" + substring);
                if (substring.equals("00")) {
                    boolean kaiguan = (boolean) SpfUtils.get(MainActivity.this, "kaiguan", false);
                    if (kaiguan) {
                        SpfUtils.put(MainActivity.this, "kaiguan", false);
                    } else {
                        SpfUtils.put(MainActivity.this, "kaiguan", true);
                    }
                    Toast.makeText(MainActivity.this, "Set boot if APP is required to confirm success！", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(MainActivity.this, "Setting boot to require APP confirmation failed！", Toast.LENGTH_SHORT).show();
                }
            } else if (guanjianzi.equals("0A")) {
                //割草机开机APP确认下发
                String substring = str3.substring(20, 22);
                Log.e("88", "开机APP确认" + substring);
                if (substring.equals("00")) {
                    Toast.makeText(MainActivity.this, "Lawnmower boot APP confirmed successful！", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(MainActivity.this, "Lawnmower boot APP confirms transmission failure！", Toast.LENGTH_SHORT).show();
                }


            } else if (guanjianzi.equals("0B")) {
                //预约失败上报
                String substring = str3.substring(20, 22);
                Log.e("88", "预约失败上报" + substring);


                if (substring.equals("00")) {
                    Toast.makeText(MainActivity.this, "Failed appointment reported successful！", Toast.LENGTH_SHORT).show();


                } else {
                    Toast.makeText(MainActivity.this, "Failed appointment reported！", Toast.LENGTH_SHORT).show();
                }

                String yuyueshibaishangbao = FaSong.yuyueshibaishangbao();
                MyEvent events4 = new MyEvent();
                events4.setType("message");
                events4.setContent(yuyueshibaishangbao);
                EventBus.getDefault().post(events4);
            } else if (guanjianzi.equals("0C")) {
                //lAwn设置成功
                String substring = str3.substring(20, 22);
                Log.e("88", "lAwn设置成功" + substring);
                if (substring.equals("00")) {
                    MyEvent events4 = new MyEvent();
                    events4.setType("settingsuccess");
                    EventBus.getDefault().post(events4);
                    Toast.makeText(MainActivity.this, "Lawnmower   settings successfully！", Toast.LENGTH_SHORT).show();
                } else {
                    MyEvent events4 = new MyEvent();
                    events4.setType("settingerr");
                    EventBus.getDefault().post(events4);
                    Toast.makeText(MainActivity.this, "Lawnmower   settings  failure！", Toast.LENGTH_SHORT).show();
                }


            }


        }
    }

    SimpleDateFormat sdf;
    @BindView(R.id.imageView)
    ImageView imageView;
    @BindView(R.id.saomamokuai2222s)
    LinearLayout saomamokuai2222s;
    @BindView(R.id.xxx)
    TextView xxx;
    @BindView(R.id.mywork)
    RelativeLayout mywork;
    @BindView(R.id.Schedule)
    TextView Schedule;
    @BindView(R.id.layout_Schedule)
    RelativeLayout layoutSchedule;
    @BindView(R.id.Currrent)
    TextView Currrent;
    @BindView(R.id.layout_Currrent)
    RelativeLayout layoutCurrrent;
    @BindView(R.id.errs)
    TextView errs;
    @BindView(R.id.err)
    RelativeLayout err;
    @BindView(R.id.Set)
    TextView Set;
    @BindView(R.id.layout_Set)
    RelativeLayout layoutSet;
    @BindView(R.id.Sub)
    TextView Sub;
    @BindView(R.id.layout_Sub)
    RelativeLayout layoutSub;


    @BindView(R.id.blue)
    TextView blue;
    @BindView(R.id.layout_Blue)
    RelativeLayout layoutBlue;
    @BindView(R.id.About)
    RoundButton About;
    @BindView(R.id.Contact)
    RoundButton Contact;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Log.e("ddddd", "ddddd");
        sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");


        CbtManager
                .getInstance()
                .init(BaseApplication.getInstance())
                .enableLog(true);
        ButterKnife.bind(this);
        imageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        z_login_userInfoDao = new Z_Login_UserInfoDao(MainActivity.this);
        EventBus.getDefault().register(this);
//         BluetoothCommunicateThread2.isRun = false;
//        jiejiexixi("55AA0110070707070707010101000000085A0500A2");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        CbtManager.isRun = false;
        Content.isConn = false;
        first = false;
        if (btCommThread != null) {
            btCommThread.close();
        }
        CbtManager.getInstance().onDestroy(false);
        EventBus.getDefault().unregister(this);
        handler.removeCallbacksAndMessages(null);
        mHandler.removeCallbacksAndMessages(null);
    }

    private void lianjie(final BluetoothSocket bluetoothSocket) {
        connect(bluetoothSocket);
    }

    public void connect(BluetoothSocket bluetoothSocket) {

        try {
            Log.e("666", "connect()");
            btSocket = bluetoothSocket;

            Message msg = new Message();
            msg.what = 1;
            handler.sendMessage(msg);

        } catch (Exception e) {
            e.printStackTrace();
            Log.e("777", "连接中抛异常！");
            try {
                btSocket.close();
            } catch (IOException e1) {
                e1.printStackTrace();
            }
            Message msg = new Message();
            msg.what = 2;
            handler.sendMessage(msg);
        }
    }

    public void startComm() {
        CbtManager.isRun = true;
        btCommThread = new BluetoothCommunicateThread2(handler, btSocket,
                MainActivity.this);

        btCommThread.start();

    }


    public void fasong(String st) {
        Log.e("androidzhi", "发送数据" + st);
        String s = null;
        try {
            s = stringToAsciiToHexString(st);

        } catch (Exception e) {
            e.printStackTrace();
        }


        btCommThread.sendMessage(s);
    }

    public void onEventMainThread(MyEvent event) {

        if (!TextUtils.isEmpty(event.getType())) {
            if (event.getType().equals("lianjie")) {
                BluetoothSocket socket = event.getSocket();
                lianjie(socket);


            } else if (event.getType().equals("message")) {
                fasong(event.getContent());

            }


        }
    }

    private static final char[] DIGITS_UPPER = {'0', '1', '2', '3', '4', '5',
            '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};


    public static String stringToAsciiToHexString(String strAsci) throws Exception {
        final byte[] bytes = hexStringToBytes(strAsci);
        System.out.println(bytes.length + ",bytes=" + Arrays.toString(bytes));
        String strResult = HexToString(bytes);
        return strResult;
    }

    public static byte[] hexStringToBytes(String hexString) throws Exception {
        int len = hexString.length() / 2;
        byte[] b = new byte[len];

        for (int i = 0; i < len; ++i) {
            b[i] = (byte) Integer.valueOf(hexString.substring(i * 2, i * 2 + 2), 16).intValue();
        }
        return b;
    }

    public static String HexToString(byte[] inHex) {
        byte i;
        String strResult = "";
        for (i = 0; i < inHex.length; i++) {
            strResult += String.valueOf(DIGITS_UPPER[(0xF0 & inHex[i]) >>> 4]) + String.valueOf(DIGITS_UPPER[inHex[i] & 0x0F]);
            //System.out.println(i+",resultStr="+strResult);
        }
        return strResult;
    }

    @OnClick({R.id.bt_getCode3, R.id.mywork, R.id.layout_Schedule, R.id.err, R.id.About, R.id.Contact, R.id.layout_Set, R.id.layout_Currrent, R.id.layout_Blue, R.id.ins, R.id.layout_Sub})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.layout_Schedule:
                startActivity(new Intent(this, ScheduleActivity.class));

                break;
            case R.id.layout_Set:
                startActivity(new Intent(this, Setting_Activity.class));
                break;
            case R.id.layout_Sub:
//                if (!Content.isConn) {
//                    Toast.makeText(this, "Please connect to Bluetooth first.", Toast.LENGTH_SHORT).show();
//                    return;
//                }
                startActivity(new Intent(this, SubareaActivity.class));
                break;
            case R.id.ins:
                startActivity(new Intent(this, Insrall_Activity.class));
                break;
            case R.id.layout_Currrent:
//                if (!Content.isConn) {
//                    Toast.makeText(this, "Please connect to Bluetooth first.", Toast.LENGTH_SHORT).show();
//                    return;
//                }
                startActivity(new Intent(this, CurrentActivity.class));
                break;
            case R.id.layout_Blue:
//                i = 0;
//                Content.isConn = false;
//                BluetoothCommunicateThread.isRun = false;
                startActivity(new Intent(MainActivity.this, LanYaLianJieActivity.class));
//
                break;
            case R.id.About:
                startActivity(new Intent(MainActivity.this, About_Activity.class));
                break;
            case R.id.Contact:
                startActivity(new Intent(MainActivity.this, Contact_Activity.class));
                break;
            case R.id.err:
                startActivity(new Intent(MainActivity.this, ListerrActivity.class));
                break;

            case R.id.mywork:
                startActivity(new Intent(MainActivity.this, MyworkActivity.class));
                break;


        }
    }

    int popo = 0;
    Handler mHandler = new Handler();
    Runnable r = new Runnable() {

        @Override
        public void run() {
            //do something
            //每隔1s循环执行run方法
            popo++;
            Log.e("98888", "xx" + popo);
            if (popo == 60) {
                z_login_userInfoDao.deletes();
                popo = 0;

            }
            if (!CbtManager.isRun) {
//                CbtManager.getInstance().onDestroy(false);
                mimi.setText("1");
                mimi2.setText("1");
//                if (btCommThread != null) {
//                    btCommThread.close();
//                    btCommThread=null;
//                }
            } else {

            }
            String mima = (String) SpfUtils.get(BaseApplication.getInstance(), "mima", "010203040506");
//            Log.e("888", "运行中！" + mima);
            if (Content.isConn && !mima.equals("010203040506") && Content.shoudaomima) {

                String xintiao = FaSong.xintiao();
                MyEvent events4 = new MyEvent();
                events4.setType("message");
                events4.setContent(xintiao);
                EventBus.getDefault().post(events4);

            }
            mHandler.postDelayed(this, 5000);


        }
    };

    StringBuilder sb2 = new StringBuilder();

    public String jiexi1(String one) {
        sb2.delete(0, sb2.length());
        String substring1 = one.substring(0, 1);
        String substring2 = one.substring(1, 2);
        String substring3 = one.substring(2, 3);
        String substring4 = one.substring(3, 4);
        String substring5 = one.substring(4, 5);
        String substring6 = one.substring(5, 6);
        String substring7 = one.substring(6, 7);
        String substring8 = one.substring(7, 8);
        if (!substring1.equals("0")) {

            sb2.append("Signal of charging station is abnormal");
            sb2.append(",");
        }
        if (!substring2.equals("0")) {

            sb2.append("Signal of charging station is abnormal.");
            sb2.append(",");
        }
        if (!substring3.equals("0")) {
            sb2.append("Emergency stop button trigger");
            sb2.append(",");
        }
        if (!substring4.equals("0")) {
            sb2.append("The inclination angle of the machine is too large.");
            sb2.append(",");
        }
        if (!substring5.equals("0")) {
            sb2.append("The machine was picked up.");

            sb2.append(",");
        }
        if (!substring6.equals("0")) {

            sb2.append("Overload of running motor");
            sb2.append(",");
        }
        if (!substring7.equals("0")) {
            sb2.append("Mowing motor overload");

            sb2.append(",");
        }
        if (!substring8.equals("0")) {
            sb2.append("Robots working normally");
            Content.zhengchang = true;
            sb2.append(",");
        } else {
            Content.zhengchang = false;
        }

        if (sb2.toString().length() == 0) {
            return sb2.toString();
        } else {
            return sb2.toString().substring(0, sb2.toString().length() - 1);
        }

    }

    StringBuilder sb3 = new StringBuilder();

    public String jiexi2(String two) {
        sb3.delete(0, sb3.length());

        String substring1 = two.substring(0, 1);
        String substring2 = two.substring(1, 2);
        String substring3 = two.substring(2, 3);
        String substring4 = two.substring(3, 4);
        String substring5 = two.substring(4, 5);
        String substring6 = two.substring(5, 6);
        String substring7 = two.substring(6, 7);
        String substring8 = two.substring(7, 8);
        if (!substring1.equals("0")) {

            sb3.append(",");
        }
        if (!substring2.equals("0")) {
            sb3.append("Jam warning alarm");

            sb3.append(",");
        }
        if (!substring3.equals("0")) {
            sb3.append("Rainwater warning");

            sb3.append(",");
        }
        if (!substring4.equals("0")) {

            sb3.append("Battery replacement warning alarm");

            sb3.append(",");
        }
        if (!substring5.equals("0")) {
            sb3.append("Blade replacement warning alarm");
            sb3.append(",");
        }
        if (!substring6.equals("0")) {
            sb3.append("The robot left the area and reached the boundary.");

            sb3.append(",");
        }
        if (!substring7.equals("0")) {

            sb3.append("Continuous obstacles encountered in line inspection");
            sb3.append(",");
        }
        if (!substring8.equals("0")) {
//            sb3.append("No handshake signal between charging station and mowing robot.");
            sb3.append("Signal of charging station is abnormal.");

            sb3.append(",");
        }
        if (sb3.toString().length() == 0) {
            return sb3.toString();
        } else {
            return sb3.toString().substring(0, sb3.toString().length() - 1);
        }

    }

    public String jiexi3(String three) {


        String name = "";
        Integer gecaoshengyus = Integer.parseInt(three, 16);
        String shuzhi = String.valueOf(gecaoshengyus);
        if (shuzhi.equals("0")) {
            name = "Idle mode";
        }
        if (shuzhi.equals("1")) {
            name = "Automatic mowing mode";

        }
        if (shuzhi.equals("2")) {
            name = "Recharge mode";

        }
        if (shuzhi.equals("3")) {
            name = "Mowing mode along the line";

        }
        if (shuzhi.equals("4")) {
            name = "Partitioned mowing mode";

        }
        if (shuzhi.equals("5")) {
            name = "Appointment mowing mode";

        }
        if (shuzhi.equals("6")) {
            name = "Wire controlled mowing mode";

        }
        if (shuzhi.equals("7")) {
            name = "Charging mode";

        }
        if (shuzhi.equals("8")) {
            name = "Anomaly pattern";

        }
        return name;
    }

    InputDialog dia;

    public void type(String Title, final int type, final String mimi) {
        dia = new InputDialog.Builder(MainActivity.this)
                .setTitle(Title)
                .setInputDefaultText("")
                .setInputMaxWords(6)

                .setInputHint("Please input a password")
                .setPositiveButton("YES", new InputDialog.ButtonActionListener() {
                    @Override
                    public void onClick(CharSequence inputText) {
                        String mima;
                        mima = inputText.toString();
                        if (TextUtils.isEmpty(mima)) {
                            Toast.makeText(MainActivity.this, "Please input a password", Toast.LENGTH_SHORT).show();
                            return;

                        }
                        switch (type) {
                            case 1:
                                //设置
                                mima = inputText.toString();
                                Log.e("888", mima);
                                String bding = FaSong.bangding("010203040506", mima);
                                MyEvent events4 = new MyEvent();
                                events4.setType("message");
                                events4.setContent(bding);
                                EventBus.getDefault().post(events4);
                                dia.dismiss();

                                break;
                            case 2:
                                //记录下了
                                mima = inputText.toString();
                                String mi1 = mima.substring(0, 1);
                                String mi2 = mima.substring(1, 2);
                                String mi3 = mima.substring(2, 3);
                                String mi4 = mima.substring(3, 4);
                                String mi5 = mima.substring(4, 5);
                                String mi6 = mima.substring(5, 6);
                                String mi1_16 = JX_Utils.getvalue16(mi1);
                                String mi2_16 = JX_Utils.getvalue16(mi2);
                                String mi3_16 = JX_Utils.getvalue16(mi3);
                                String mi4_16 = JX_Utils.getvalue16(mi4);
                                String mi5_16 = JX_Utils.getvalue16(mi5);
                                String mi6_16 = JX_Utils.getvalue16(mi6);
//

                                String shuju = mi1_16 + mi2_16 + mi3_16 + mi4_16 + mi5_16 + mi6_16;
                                if (!shuju.equals(mimi)) {
                                    Toast.makeText(MainActivity.this, "Password error！", Toast.LENGTH_SHORT).show();
                                    dia.dismiss();
                                    Content.shoudaomima = false;
                                    finish();


                                } else {
                                    Content.shoudaomima = true;
                                    SpfUtils.put(BaseApplication.getInstance(), "mima", shuju);
                                }


                                break;
                            default:
                                break;
                        }
                    }
                })
                .setNegativeButton("cancel", new InputDialog.ButtonActionListener() {
                    @Override
                    public void onClick(CharSequence inputText) {
                        finish();
                    }
                })
                .setOnCancelListener(new InputDialog.OnCancelListener() {
                    @Override
                    public void onCancel(CharSequence inputText) {
                        // TODO
                    }
                })
                .interceptButtonAction(new InputDialog.ButtonActionIntercepter() { // 拦截按钮行为
                    @Override
                    public boolean onInterceptButtonAction(int whichButton, CharSequence inputText) {
                        if ("/sdcard/my".equals(inputText) && whichButton == DialogInterface.BUTTON_POSITIVE) {

                            // 以及return true拦截此按钮默认行为
                            return true;
                        }
                        return false;
                    }
                })
                .show();
    }

    public void chaxunmima() {
        String mi0 = (String) SpfUtils.get(BaseApplication.getInstance(), "mima", "010203040506");
        String bangding6 = FaSong.huoqupincode(mi0);
        MyEvent events36 = new MyEvent();
        events36.setType("message");
        events36.setContent(bangding6);
        EventBus.getDefault().post(events36);

    }


}
